{% extends 'IMTDashboardBundle::layout.html.twig' %}

{% block main_title %}Planning{% endblock %}

{% block include_plugin_style %}
<link rel="stylesheet" href="{{ asset('plugins/fullcalendar/fullcalendar.css') }}" media="screen" />
<link rel="stylesheet" href="{{ asset('plugins/fullcalendar/fullcalendar.print.css') }}" media="print" />
{% endblock %}

{% block include_style %}
<link rel="stylesheet" href="{{ asset('bundles/imtdashboard/css/fullcalendar-event-colors.css') }}" media="screen" />
<style>
/*** Agenda ***/
.account-box {
	width:16px; 
	height: 16px; 
	float:left; 
	margin-right:8px;
}

#widget-datepicker .ui-datepicker{
	width: 100%;
	box-shadow: none;
}

.account-content-box{
	border-top:0; 
	cursor:pointer;	
}
#wrapper #content-inner {
	background-image: none;
}

.popover {
	width:auto;
}
</style>
{% endblock %}

{% block include_script %}
<script src="{{ asset('plugins/fullcalendar/fullcalendar.js') }}"></script>
<script>
var IMT_EVENTS = {% render 'IMTDashboardBundle:Calendar:allEvent' %};

$(document).ready(function() {
	$('[rel=tooltip]').tooltip();
	
	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();

	$('#widget-datepicker').datepicker({
		prevText: "Précedent",
        nextText: "Suivant",
        currentText: "Aujourd\'hui",
        monthNames: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aoüt", "Septembre", "Octobre", "Novembre", "Décembre"],
        monthNamesShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jui", "Aou", "Sep", "Oct", "Nov", "Dec"],
        dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
        dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
        dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
        weekHeader: "Wk",
        dateFormat: "yy-mm-dd",
        firstDay: 1,
        showButtonPanel: false,
        onSelect: function(dateText, inst) {
            var d = new Date(dateText);
            $('#calendar').fullCalendar('gotoDate', d);
        }
    });
	
	$('#calendar').fullCalendar({
		header: {
			left: 'prev next prevYear nextYear today',
			center: 'title',
			right: 'agendaDay,agendaWeek,month'
		},
		titleFormat: {
			month: 'MMMM yyyy',
			week: "d MMMM[ yyyy]{ '&#8212;'d MMMM yyyy}",
			day: 'dddd d MMMM yyyy'
		},
		columnFormat: {
			month: 'ddd',
			week: 'ddd d MMMM',
			day: 'dddd d MMMM'
		},
		monthNames: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aoüt", "Septembre", "Octobre", "Novembre", "Décembre"],
        monthNamesShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jui", "Aou", "Sep", "Oct", "Nov", "Dec"],
        dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
        dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
		buttonText: {
			prev: '&nbsp;&#9668;&nbsp;',
			next: '&nbsp;&#9658;&nbsp;',
			prevYear: '&nbsp;&lt;&lt;&nbsp;',
			nextYear: '&nbsp;&gt;&gt;&nbsp;',
			today: 'Aujourd\'hui',
			month: 'Mois',
			week: 'Semaine',
			day: 'Jour'
		},
		timeFormat: 'H:mm',
		selectable: true,
		selectHelper: true,
		select: function(start, end, allDay) {
			/*var title = prompt('Event Title:');
			if (title) {
				calendar.fullCalendar('renderEvent',
					{
						title: title,
						start: start,
						end: end,
						allDay: allDay
					},
					true // make the event "stick"
				);
			}
			calendar.fullCalendar('unselect');
			*/
		},
		editable: true,
		events: IMT_EVENTS,   
		viewDisplay: function(view) {
			$('.popover .close').click();
		},                     
        eventClick: function(calEvent, jsEvent, view) {
           	if(!calEvent.isOpen){
        		$('.popover .close').click();

        		var content = '<div class="popover-loader" style="text-align:center; width:300px;"><img style="padding:50px 0px;" alt="Chargement ..." src="{{ asset('assets/images/preloaders/3.gif') }}" /></div>';
        		if(!calEvent.isUpdate)
            		content = calEvent.content;
               
	            $(jsEvent.currentTarget).popover({
	    			content: content,
	    			title: calEvent.title+' <span class="close pull-right">×</span>',
	    			html: true,
	    			trigger: 'manual',
	    			placement: 'top',
	    			container: 'body'
	    	    });
	
	            calEvent.isOpen = true;
	            $(jsEvent.currentTarget).popover('show');

	            if(calEvent.isUpdate){
		            $.ajax({
						url: '{{ path('accueil_event_popover') }}',
						global: false,
						type: "POST",
						data: {
							idEvent: calEvent.id,
							type: calEvent.type,
							classType: calEvent.classType
				       	},
						dataType: "html",
						async:true,
						success: function(r) {	
							$('.popover-loader').parent().html(r);
							calEvent.isUpdate = false;				
							calEvent.content = r;
						},
						error: function(){
							alert('erreur serveur');
						},
						complete: function(){	
						}
					});
           		}
	
	            $('.popover .close').click(function(e){
		            if(calEvent.isOpen){
		                calEvent.isOpen = false;
			    		$(jsEvent.currentTarget).popover('destroy');
	                }
		    	});
           	}
            
	        /*$("#modalEventTitle").html(calEvent.title);
	        $("#modal_event_content").html(calEvent.content);
	        $("#owner").html(calEvent.owner_name+" ");
	        $("#owner").append(calEvent.owner_firstname);
	        $("#event_start").append(calEvent.start_f);	
	        $("#event_end").append(calEvent.end_f);	
	        $("#modalEventFooter a").attr('href','{{ path('event_accueil') }}'+calEvent.id);
            $("#modalEvent").modal('show');*/		
	    },
	    eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) {
		    $.ajax({
				url: '{{ path('accueil_planning_update', {'type':'move'}) }}',
				global: false,
				type: "POST",
				data: {
					idEvent: event.id,
					type: event.type,
					classType: event.classType,
					dayDelta:dayDelta,
					minuteDelta:minuteDelta,
					allDay:(allDay ? 1 : 0),
		       	},
				dataType: "json",
				async:true,
				success: function(r) {					
					if(r.response == 200){

					} else if(r.response == 400){
					
					} else if(r.response == 500){
						alert(r.params);
					}
				},
				error: function(){
					alert('erreur serveur');
				},
				complete: function(){	
					event.isUpdate = true;
					event.isOpen = false;
				}
			});
	    },
	    eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
	    	$.ajax({
				url: '{{ path('accueil_planning_update', {'type':'resize'}) }}',
				global: false,
				type: "POST",
				data: {
					idEvent:event.id,
					type: event.type,
					classType: event.classType,
					dayDelta:dayDelta,
					minuteDelta:minuteDelta,
		       	},
				dataType: "json",
				async:true,
				success: function(r) {					
					if(r.response == 200){

					} else if(r.response == 400){
					
					} else if(r.response == 500){
						alert(r.params);
					}
				},
				error: function(){
					alert('erreur serveur');
				},
				complete: function(){	
					event.isUpdate = true;
					event.isOpen = false;
				}
			});
	    }
	});

	//$("#calendar").fullCalendar( 'renderEvent',{title: 'Test add event',start: new Date(2012, 6, 10),end: new Date(2012, 6, 12), className: ["test"], end: new Date(2012, 7,7)},true);

	// Définition de l'evenement lors du clic sur un compte
	$('#listAccount .account-content-box').click(function(){
		updateAccountSelection($(this).find('.account-box'), true);
	});      

	// Mise à jour de tout les comptes au chargement de la page
	$('#listAccount .account-content-box').each(function(){
		updateAccountSelection($(this).find('.account-box'), false);
	});


	/*$('body').click(function(e){
		$('.popover').remove();
    });*/
});

function updateAccountSelection(account, isUpdate){
	if(isUpdate){
		if(parseInt(account.data('display-account'))){
			account.data('display-account', 0);
			account.removeClass(account.data('color-account'));
		} else {
			account.data('display-account', 1);
			account.addClass(account.data('color-account'));
		}
		
		updateAccountSelection(account, false);
		return;
	}
	
	// Récupération des events
	var events = $("#calendar").fullCalendar('clientEvents');
	// Réinitialisation de la liste d'events
	var listEvents = (typeof account.data('events') != 'undefined') ? account.data('events') : {};

	$.each(events,function(i,event){
		if(parseInt(event.account) == parseInt(account.data('id-account')) && typeof event.display){
			var newEvent = $.extend({display:true}, event);
			listEvents[newEvent.id] = newEvent;
		}
	});	

	account.data('events', listEvents);

	var displayEvents = Array();
	$.each(listEvents, function(id, event){
		if(parseInt(account.data('display-account')) == 1 && !event.display){
			event.display = true;
			displayEvents.push(event);
		} else if(parseInt(account.data('display-account')) == 0 && event.display){
			event.display = false;
			$("#calendar").fullCalendar('removeEvents', id);
		}
	});

	$("#calendar").fullCalendar( 'addEventSource', displayEvents);

}
</script>
{% endblock %}

{% block content %}
<div id="content">
	<div id="content-outer">
		<div id="content-inner">
			<section id="main" class="clearfix" style="margin:0px 20px;">
		        <div id="main-header" class="page-header">
					<h1 id="main-heading">
		         		Planning <span>Le temps est comme l'argent, ne le perdez pas et vous en aurez ...</span>
		            </h1>
		        </div>
	        
				<div class="row-fluid">
					<div class="span10">
						<div class="widget">
				        	<div class="widget-header">
				            	<span class="title">
				                	<i class="icon-calendar"></i> Mon planning
				            	</span>
				            	<div class="toolbar">
									<!-- <span class="btn"><i class="icon-refresh"></i></span>-->
									<div class="btn-group">
										<span data-toggle="dropdown" class="btn dropdown-toggle">
											<i class="icon-plus"></i> Ajouter un événement
										</span>
										<ul class="dropdown-menu pull-right dropdown-menu-left">
		                                	<li><a href="{{ path('event_accueil') }}"><i class="icol-calendar-2"></i> Nouvel événement</a></li>
{# 		                                	<li><a href="{{ path('task_accueil') }}"><i class="icol-clipboard-text"></i> Nouvelle tâche</a></li>#}
	                                        <li><a href="{{ path('call_accueil') }}"><i class="icol-mobile-phone"></i> Nouvel appel téléphonique</a></li>
	                                        <li><a href="{{ path('meeting_accueil') }}"><i class="icol-projection-screen-present"></i> Nouvelle réunion</a></li>
										</ul>
									</div>
								</div>
				        	</div>
				        	<div class="widget-content no-padding no-border">
				        	    <div id="calendar"></div>
				        	</div>
				    	</div>		
					</div>
					<div class="span2">
						<div class="widget">
							<div id="widget-datepicker"></div>
						</div>
					
						<div class="widget">
				        	<div class="widget-header">
				            	<span class="title">
				                	<i class="icon-book"></i> Mes comptes
				            	</span>
				            	<div class="toolbar">
									<div class="btn-group">
										<span data-toggle="dropdown" class="btn dropdown-toggle">
											<i class="icon-cog"></i>
										</span>
										<ul class="dropdown-menu pull-right dropdown-menu-left">
											<li><a href="{{ path('account_home') }}"><i class="icol-book-addresses"></i> Gérer mes comptes</a></li>
											<!-- <li><a href="#"><i class="icol-tag-blue"></i> Gérer mes libellés</a></li>-->
										</ul>
									</div>
								</div>
				        	</div>
				        	<div class="widget-content no-padding">
							{% render 'IMTAccountBundle:Default:list' with {'active' : true} %}
							</div>
				    	</div>	
					</div>
				</div>
			</section>
	   	</div>
	</div>
</div>

<div class="modal hide fade" id="modalEvent">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3 id="modalEventTitle"></h3>
    </div>
    <div class="modal-body"  id="modalEventContent">
    	<div style="width:30%; float:left;">
    		<h4>Créateur</h4>
    		<div class="span3 avatar" style="margin-top:15px; margin-bottom:0px!important;">
				<ul class="thumbnails">
					<li style="margin-left:10px!important;  margin-bottom:0px!important;">
						<a class="thumbnail" href="#">
							<img alt="" src="{{ asset('bundles/imtevent/images/avatar1.jpg') }}">
						</a>
					</li>
				</ul>	
			</div>
			<div id="owner" style="margin-left:13px;"></div>
        </div>
        <div style="width:70%; float:right;">
        	<h4>Horaires</h4>
        	<div style="margin-top:13px;">
        		<div id="event_start"><i>Début :</i> </div>
        		<div id="event_end"><i>Fin :</i> </div>
        	</div>
        	<br>
        	<h4>Contenu de l'évenement</h4>
        	<div id="modal_event_content" style="margin-top:13px;"></div>
        </div>
    </div>
    <div class="modal-footer" id="modalEventFooter">
        <a href="#" class="btn btn-primary">Voir détail</a>
    </div>
</div>
{% endblock %}